<?php
namespace Manage\Controller;
use Manage\Model\B2cOrdersModel;
/**
 * Class 页面管理-首页轮播
 * @package Admin\Controller
 */

class OrdersController extends BaseController  {


    /**
     * 店铺订单列表
     */
    public function orderList(){


        $p = I('p',1,'intval');
        $view = I('get.view',0,'intval');

        //文字描述
        $isDes = array(
            0=>'待发货',
            1=>'已发货',
            2=>'已收货',
            3=>'待支付',
            4=>'已作废',
            5=>'已完成',
            6=>'全部',
        );


        $Model = new B2cOrdersModel();
        $orderList = $Model->orderList($p,$view);

        $this->assign('view',$view);
        $this->assign('isDes',$isDes[$view]);
        $this->assign('page',$orderList['page']);// 赋值分页输出
        $this->assign('payList',$orderList['list']);
        $this->display('Orders/orderList');

    }

    /**
     *
     * 订单详情
     *
     */

    public function  orderDetail(){

        $Model = new B2cOrdersModel();

        $orDetail = $Model->orderDetail(I('get.id'));


        //售后申请商品
        foreach ($orDetail['product'] as $k=>$value){

            $is_refund[$k] = M('b2c_refund_money_goods mg')
                ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.status'=>['not in','0,6,7'],
                    'm.type'=>'1'])
                ->field('it.*,m.price as backprice,mg.num')
                ->order('m.id desc')
                ->find();
            if(empty($is_refund[$k])){
                unset($is_refund[$k]);
                continue;
            }


            $is_refund[$k]['istype'] = '发货前：退款';
            $is_refund[$k]['bn'] = $value['bn'];
            $is_refund[$k]['name'] = $value['name'];
            $is_refund[$k]['barcode'] = $value['barcode'];
            $is_refund_tree[$k]['price'] = $value['price'];
            $is_refund[$k]['sendnum'] = $value['sendnum'];
            $is_refund[$k]['nums'] = $value['nums'];
            $is_refund[$k]['amount'] = $value['amount'];

        }
        //发货后 售后退款
        foreach ($orDetail['product'] as $k=>$value){

            $is_refund_two[$k] = M('b2c_refund_money_goods mg')
                ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.status'=>['not in','0,6,7'],
                    'm.type'=>'2'])
                ->field('it.*,m.price as backprice,mg.num')
                ->order('m.id desc')
                ->find();
            if(empty($is_refund_two[$k])){
                unset($is_refund_two[$k]);
                continue;
            }


            $is_refund_two[$k]['istype'] = '发货后：售后退款';
            $is_refund_two[$k]['bn'] = $value['bn'];
            $is_refund_two[$k]['name'] = $value['name'];
            $is_refund_tree[$k]['price'] = $value['price'];
            $is_refund_two[$k]['barcode'] = $value['barcode'];
            $is_refund_two[$k]['sendnum'] = $value['sendnum'];
            $is_refund_two[$k]['nums'] = $value['nums'];
            $is_refund_two[$k]['amount'] = $value['amount'];

        }

        //发货后 售后退货退款
        foreach ($orDetail['product'] as $k=>$value){

            $is_refund_tree[$k] = M('b2c_refund_money_goods mg')
                ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.status'=>['not in','0,6,7'],
                    'm.type'=>'3'])
                ->field('it.*,m.price as backprice,mg.num')
                ->order('m.id desc')
                ->find();

            if(empty($is_refund_tree[$k])){
                unset($is_refund_tree[$k]);
                continue;
            }


            $is_refund_tree[$k]['istype'] = '发货后：退货退款';
            $is_refund_tree[$k]['bn'] = $value['bn'];
            $is_refund_tree[$k]['name'] = $value['name'];
            $is_refund_tree[$k]['price'] = $value['price'];
            $is_refund_tree[$k]['barcode'] = $value['barcode'];
            $is_refund_tree[$k]['sendnum'] = $value['sendnum'];
            $is_refund_tree[$k]['nums'] = $value['nums'];
            $is_refund_tree[$k]['amount'] = $value['amount'];

        }



        if($orDetail['status']===0){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }
        $this->assign('isrefund',$is_refund);
        $this->assign('isrefundtwo',$is_refund_two);
        $this->assign('isrefundtree',$is_refund_tree);
        $this->assign('orDetail',$orDetail);
        $this->display('Orders/orderDetail');

    }

    /**
     * 订单备注
     */
    public function orderMark(){

        $Model = new B2cOrdersModel();
        $result = $Model->markList(I('get.id'));
        $this->assign('orderMark',$result);
        $this->assign('order_id',I('get.id'));
        $this->display('Orders/orderMark');

    }



    /**
     * 订单日志
     */
    public function orderLog(){
        $Model = new B2cOrdersModel();

        $result = $Model->ordreLog(I('get.id'));

        if($result['status']===0){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }

        $this->assign('order_id',I('get.id'));
        $this->assign('logList',$result);
        $this->display('Orders/orderLog');
    }



    public function eExcel(){

        $Model = new B2cOrdersModel();
        $title = array(
            array('order_id','订单号'),
            array('local_name','门店名称'),
            array('is_zt','是否自提'),
            array('createtime','下单时间'),
            array('shipping','配送方式'),
            array('ship_time','配送时间'),
            array('memo','客户备注'),
            array('mark','订单备注'),
            array('login_account','会员名称'),
            array('payment','支付方式'),
            array('ship_name','收货人'),
            array('ship_mobile','收货人手机'),
            array('cost_freight','配送费用'),
            array('total_amount','订单总额'),
            array('pay_status','付款状态'),
            array('ship_status','发货状态')


        );
        $data = $_POST;

        $datStr = implode(',',$data['checkName']);
        //查询数据
        $strData['o.order_id'] = array('in',$datStr);


        $seData = M('b2c_orders o')
            ->join("left join ".C('DB_PREFIX')."b2c_members m on o.member_id = m.member_id")
            ->join("left join ".C('DB_PREFIX')."webpos_local_store ls on ls.local_id = o.local_id")
            ->where([$strData])
            ->field("o.order_id,ls.local_name,o.is_zt,o.createtime,o.shipping,o.ship_time,o.memo,o.mark_text,m.nickname,o.payment,o.ship_name,
            o.ship_mobile,o.cost_freight,o.total_amount,o.pay_status,o.ship_status")->select();



        foreach ($seData as $k=>$item){
            $seData[$k]['order_id'] = "'".$item['order_id'];
            $seData[$k]['local_name'] = $item['local_name'];
            $seData[$k]['is_zt'] = $item['is_zt']?"自提订单":"普通订单";
            $seData[$k]['createtime'] = "'".date('Y-m-d H:i:s',$item['createtime']);
            $seData[$k]['shipping'] = $item['shipping']; //配送方式
            $seData[$k]['ship_time'] = $item['ship_time'];//配送时间
            $seData[$k]['memo'] = $item['memo'];//客户附言

            if(!empty($item['mark_text'])){
                $mark =unserialize( $item['mark_text']);
                $markContent = end($mark);
            }
            $seData[$k]['mark_text'] =  $markContent['mark_text'];
            $seData[$k]['login_account'] = $item['nickname'];//会员名称
            $seData[$k]['payment'] = $item['payment'];//支付方式
            $seData[$k]['ship_name'] = $item['ship_name'];//收货人姓名
            $seData[$k]['ship_mobile'] = "'".$item['ship_mobile'];//收货手机
            $seData[$k]['cost_freight'] = $item['cost_freight'];//配送费用
            $seData[$k]['total_amount'] = $item['total_amount'];//订单总额

            if($item['pay_status']==1){
                $item['pay_status'] = "已支付";
            }else if($item['pay_status']==0){
                $item['pay_status'] = "未支付";
            }

            $seData[$k]['pay_status'] = $item['pay_status'];//付款状态

            if($item['ship_status']==1){
                $item['ship_status'] = "已发货";
            }else if($item['ship_status']==2){
                $item['ship_status'] = "部分发货";
            }else if($item['ship_status']==0){
                $item['ship_status'] = "未发货";
            }

            $seData[$k]['ship_status'] = $item['ship_status'];//发货状态


        }

        $this->exportexcel('订单',$title,$seData);


    }


    public function exprotAllOrder(){

        $view = I('get.view',0,'intval');
        $sub = array(
            0 => array('o.pay_status' => '1', 'o.ship_status' => array('in', array('0', '2')), 'o.status' => 'active'),// 待发货
            1 => array('o.pay_status' => '1', 'o.ship_status' => '1', 'o.status' => 'active'),// 已发货
            2 => array('o.pay_status' => '1', 'o.ship_status' => '1', 'o.received_status' => '1', 'o.status' => 'active'), //已收货  部分发货，不能确认收货 提示货没发完，收货定时任务，判断 发货状态是 1
            3 => array('o.pay_status' => '0', 'o.status' => 'active'),//待支付
            4 => array('o.status' => 'dead'),//已经作废【未支付订单超时】，定时返回库存
            5 => array('o.status' => 'finish'),//已完成
            //6=>array('o.pay_status'=>'1','o.is_zt'=>1,'o.status'=>'active','o.local_id'=>session('userInfo.local_id')),//店铺自提  [完成按钮]  状态 finish 库存操作
            6 => ' 1=1',
        );
        $where[] = $sub[$view];
        $title = array(
            array('order_id','订单号'),
            array('local_name','门店名称'),
            array('is_zt','是否自提'),
            array('createtime','下单时间'),
            array('shipping','配送方式'),
            array('ship_time','配送时间'),
            array('memo','客户备注'),
            array('mark','订单备注'),
            array('login_account','会员名称'),
            array('payment','支付方式'),
            array('ship_name','收货人'),
            array('ship_mobile','收货人手机'),
            array('cost_freight','配送费用'),
            array('total_amount','订单总额'),
            array('pay_status','付款状态'),
            array('ship_status','发货状态')
        );

        $orderList =  M('b2c_orders o')->field("o.*,m.login_account")
            ->join("left join " . C('DB_PREFIX') . "pam_members m on o.member_id = m.member_id")
            ->join("left join ". C('DB_PREFIX')."webpos_local_store ls on ls.local_id = o.local_id")
            ->where($where)
            ->order('o.createtime desc')->select();

        foreach ($orderList as $k=>$item) {
            $seData[$k]['order_id'] = "'" . $item['order_id'];
            $seData[$k]['local_name'] = $item['local_name'];
            $seData[$k]['is_zt'] = $item['is_zt'] ? "自提订单" : "普通订单";
            $seData[$k]['createtime'] = "'" . date('Y-m-d H:i:s', $item['createtime']);
            $seData[$k]['shipping'] = $item['shipping']; //配送方式
            $seData[$k]['ship_time'] = $item['ship_time'];//配送时间
            $seData[$k]['memo'] = $item['memo'];//客户附言

            if (!empty($item['mark_text'])) {
                $mark = unserialize($item['mark_text']);
                $markContent = end($mark);
            }
            $seData[$k]['mark_text'] = $markContent['mark_text'];
            $seData[$k]['login_account'] = $item['login_account'];//会员名称
            $seData[$k]['payment'] = $item['payment'];//支付方式
            $seData[$k]['ship_name'] = $item['ship_name'];//收货人姓名
            $seData[$k]['ship_mobile'] = "'" . $item['ship_mobile'];//收货手机
            $seData[$k]['cost_freight'] = $item['cost_freight'];//配送费用
            $seData[$k]['total_amount'] = $item['total_amount'];//订单总额

            if ($item['pay_status'] == 1) {
                $item['pay_status'] = "已支付";
            } else if ($item['pay_status'] == 0) {
                $item['pay_status'] = "未支付";
            }

            $seData[$k]['pay_status'] = $item['pay_status'];//付款状态

            if ($item['ship_status'] == 1) {
                $item['ship_status'] = "已发货";
            } else if ($item['ship_status'] == 2) {
                $item['ship_status'] = "部分发货";
            } else if ($item['ship_status'] == 0) {
                $item['ship_status'] = "未发货";
            }
            $seData[$k]['ship_status'] = $item['ship_status'];

        }
        $isDes = array(
            0=>'待发货订单',
            1=>'已发货订单',
            2=>'已收货订单',
            3=>'待支付订单',
            4=>'已作废订单',
            5=>'已完成订单',
            6=>'全部订单',
        );

        $this->exportexcel($isDes[$view], $title, $seData);

    }


    public function exportexcel($expTitle,$expCellName,$expTableData){

        $data_time = date('Y-m-d',time());
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName =$data_time.$expTitle;//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;


    }



}